package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"news-hub/models"
)

type NewController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewController) Add() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	time := c.GetString("time")
	cut := c.GetString("cut")
	new := models.New{
		Id:    id,
		Title: title,
		Time:  time,
		Cut:   cut,
	}
	err := models.DB.Create(&new).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
func (c *NewController) List() {
	var new []models.New
	err := models.DB.Find(&new).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: new,
		}
		c.ServeJSON()
		return
	}
}
func (c *NewController) Up() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	time := c.GetString("time")
	cut := c.GetString("cut")
	new := models.New{
		Id:    id,
		Title: title,
		Time:  time,
		Cut:   cut,
	}
	err := models.DB.Where("id=?", id).Updates(&new).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.New{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
